<?php
class AdminController extends Zend_Controller_Action{

	protected $auth_instance;

    public function init(){
    	$this->auth_instance = Zend_Auth::getInstance();
    	$this->_helper->layout->setLayout('admin-layout');
    }

    public function indexAction(){
    }

    public function loginAction(){

    	$loginForm = new Application_Form_AdminLogin();
    	$request = $this->getRequest();

    	if ($request->isPost()) {
    		if ($loginForm->isValid($request->getPost())) {
    			$auth_result = $this->_processAuth($loginForm->getValues());
				if ($auth_result == '') {
                    // We're authenticated! Redirect to the home page
					$this->_helper->FlashMessenger('Successful Login!');
                    $this->_helper->redirector('index', 'index');
                } else {
                		switch ($auth_result) {

                			case Zend_Auth_Result::FAILURE_IDENTITY_NOT_FOUND:
                				/** do stuff for nonexistent identity **/
                				$this->view->errorMessage = 'User non-existent!';
                				break;

                			case Zend_Auth_Result::FAILURE_CREDENTIAL_INVALID:
                				/** do stuff for invalid credential **/
                				$this->view->errorMessage = 'Invalid email/password!';
                				break;

                			default:
                				/** do stuff for other failure **/
                				$this->view->errorMessage = 'Login process failed!';
                				break;
                		}
                }
    		}

    	}
    	$this->view->loginForm = $loginForm;
    }

    public function logoutAction(){
    	$this->auth_instance->clearIdentity();
    	$this->_helper->redirector('index', 'index'); // back to login page
    }

    protected function _getAuthAdapter() {

    	$dbAdapter = Zend_Db_Table::getDefaultAdapter();
    	$authAdapter = new Zend_Auth_Adapter_DbTable($dbAdapter);

    	$authAdapter->setTableName('user')
    		->setIdentityColumn('email')
    		->setCredentialColumn('password')
    		->setCredentialTreatment('SHA1(CONCAT(?,password_salt))');

    	return $authAdapter;
    }

    protected function _processAuth($values){

    	// Get our authentication adapter and check credentials
    	$adapter = $this->_getAuthAdapter();

    	$adapter->setIdentity($values['email']);
    	$adapter->setCredential($values['password']);

    	$result = $this->auth_instance->authenticate($adapter);
    	if ($result->isValid()) {

    		$user = $adapter->getResultRowObject();
    		$this->auth_instance->getStorage()->write($user);
    		
    		return '';
    	} else {
    		return $result->getCode();
    	}

    }

    public function productsAction(){
    	$productMapper = new Application_Model_ProductMapper();
    	$categMapper = new Application_Model_CategoryMapper();
    	$products = $productMapper->fetchAll();
    	
    	$this->view->contentProducts = "<a href='/admin/addProduct'>Adauga Produs</a><br />";
    	
    	if (empty($products)){
    		$this->view->contentProducts.= "<h4>Nu exista produse!</h4>";
    	} else {
    		$this->view->contentProducts.= "<table><thead style='font-weight:bold;'>
    				<tr><td>ID</td> <td>Nume</td> <td>Categorie</td> 
    				<td>In stoc</td> <td>Pret</td> <td>Locatie Poza</td> <td>Actiuni</td></tr></thead>";
    		foreach($products as $product){
    			$productCateg = new Application_Model_Category();
    			$categMapper->find($product->getId_category(), $productCateg);
    			
    			$this->view->contentProducts.="<tr>";
    		
    			$this->view->contentProducts.="<td>".$product->getId()."</td>";
    			$this->view->contentProducts.="<td>".$product->getName()."</td>";
    			$this->view->contentProducts.="<td>".$productCateg->getName()."</td>";
    			$this->view->contentProducts.="<td>".$product->getNbr_pieces()."</td>";
    			$this->view->contentProducts.="<td>".$product->getPrice()."</td>";
    			$this->view->contentProducts.="<td>".$product->getPicture_location()."</td>";
    			
    			$this->view->contentProducts.="<td><a id='".$product->getId()."' class='deleteProduct' href='#'>Sterge</a> /
    												<a id='".$product->getId()."' class='editProduct' href='#'>Modifica</a> / 
    												<a id='".$product->getId()."' class='specs' href='#'>Specificatii</a></td>";
    		
    			$this->view->contentProducts.="</tr>";
    		}
    		$this->view->contentProducts.= "</table>";
    	}
    }
    
    public function addproductAction(){
    	$request = $this->getRequest();
    	$form = new Application_Form_AddProduct();
    	 
    	
    	if ($this->getRequest()->isPost()) {
    		if ($form->isValid($request->getPost()) && $form->getValue('id_category') != 0) {
    			$product = new Application_Model_Product($form->getValues());
    			$mapper  = new Application_Model_ProductMapper();
    			$mapper->save($product);
    			return $this->_helper->redirector('products');
    		} 
    		if ($form->getValue('id_category') == 0) {
    			$this->view->errorMessage = 'Va rugam selectati o categorie!';
    			$this->view->form = $form;
    			return;
    		}
    	}
    	$this->view->form = $form;    	
    }
    
    public function delproductAction(){
    	$productId = $this->_getParam('id');
    	$mapper = new Application_Model_ProductMapper();
    	
    	if ($mapper->delete($productId) == 1){
    		//One row was deleted
    		return $this->_helper->redirector('products');
    	} else {
    		return $this->_helper->redirector('index');
    	}
    }
    
    public function editproductAction(){
    	$productId = $this->_getParam('id');
    	$productMapper = new Application_Model_ProductMapper();
    	$request = $this->getRequest();
    	$form = new Application_Form_AddProduct();
    	
    	$product = new Application_Model_Product();
    	$productMapper->find($productId, $product);
    	
    	$form->getElement('name')->setValue($product->getName());
    	$form->getElement('picture_location')->setValue($product->getPicture_location());
    	$form->getElement('price')->setValue($product->getPrice());
    	$form->getElement('nbr_pieces')->setValue($product->getNbr_pieces());
    	$form->getElement('id_category')->setValue($product->getId_category());
    	$form->getElement('submit')->setLabel('Modifica Produs');
    	
    	if ($this->getRequest()->isPost()) {
    		if ($form->isValid($request->getPost()) && $form->getValue('id_category') != 0) {
    			$product = new Application_Model_Product($form->getValues());
    			$product->setId($productId);
    			
    			$productMapper->save($product);
    			return $this->_helper->redirector('products');
    		} else {
    			$this->view->errorMessage = 'Va rugam selectati o categorie!';
    			$this->view->form = $form;
    			return;
    		}
    	}
    	$this->view->form = $form;
    }
   
	public function editspecsAction(){
		
		$productId = $this->_getParam('id');
		$productMapper = new Application_Model_ProductMapper();
		$specificationsMapper = new Application_Model_SpecificationMapper();
		$product = new Application_Model_Product();
		$productMapper->find($productId, $product);
		
		
		$specs = $specificationsMapper->fetchAllFor($productId);
		$this->view->viewContent = '<a id="'.$productId.'" href="#" class="addSpec">Adauga</a>';
		
		if (empty($specs)){
			$this->view->viewContent.= "<h3> Nu exista specificatii pentru acest produs</h3>";
		} else {
			$this->view->viewContent .= "<h3> Specificatii pentru ". $product->getName()." </h3>";
			$this->view->viewContent .= "<table><thead style='font-weight:bold;'>
    				<tr><td>Categorie</td> <td>Nume</td> <td>Valoare</td> <td>Actiuni</td></tr></thead>";
			
			foreach($specs as $spec){
			
				$this->view->viewContent.="<tr>";
			
				$this->view->viewContent.="<td>".$spec->getSpec_category()."</td>";
				$this->view->viewContent.="<td>".$spec->getSpec_name()."</td>";
				$this->view->viewContent.="<td>".$spec->getSpec_value()."</td>";
				$this->view->viewContent.="<td>
						<a id='".$spec->getId_spec()."_".$productId."' class='delSpec' href='#'>Sterge</a> /
    					<a id='".$spec->getId_spec()."_".$productId."' class='changeSpec' href='#'>Modifica</a></td>";
			
				$this->view->viewContent.="</tr>";
			}
			$this->view->viewContent.= "</table>";
		}
	}
	
	public function addspecAction(){
		
		$productId = $this->_getParam('id');
		$productMapper = new Application_Model_ProductMapper();
		$specificationsMapper = new Application_Model_SpecificationMapper();
		$product = new Application_Model_Product();
		$productMapper->find($productId, $product);
		$form = new Application_Form_AddSpec();
		$request = $this->getRequest();
		
		$this->view->productName = $product->getName();
		
		if ($this->getRequest()->isPost()) {
			if ($form->isValid($request->getPost())) {
 				$spec = new Application_Model_Specification($form->getValues());
 				
 				$spec->setId_product($productId);
 				$specificationsMapper->save($spec);
 				
				return $this->_helper->redirector->gotoUrl("admin/editSpecs/id/".$productId);				
			} else {
				$this->view->errorMessage = 'Va rugam completati toate campurile!';
				$this->view->form = $form;
				return;
			}
		}
		$this->view->form = $form;
	}

	public function changespecAction(){
		$ids = explode("_", $this->_getParam('id'));
		
		$specificationsMapper = new Application_Model_SpecificationMapper();
		$productMapper = new Application_Model_ProductMapper();
		
		$spec = new Application_Model_Specification();
		$product = new Application_Model_Product();
		
		$specificationsMapper->find($ids[0], $spec);
		$productMapper->find($ids[1], $product);
		
		$form = new Application_Form_AddSpec();
		
		$form->getElement('spec_category')->setValue($spec->getSpec_category());
		$form->getElement('spec_name')->setValue($spec->getSpec_name());
		$form->getElement('spec_value')->setValue($spec->getSpec_value());
		$form->getElement('submit')->setLabel('Modifica Specificatie');
		
		$request = $this->getRequest();
		
		$this->view->productName = $product->getName();
		if ($this->getRequest()->isPost()) {
			if ($form->isValid($request->getPost())) {
				$newSpec = new Application_Model_Specification($form->getValues());
					
				$newSpec->setId_product($product->getId());
				$newSpec->setId_spec($spec->getId_spec());
				$specificationsMapper->save($newSpec);
					
				return $this->_helper->redirector->gotoUrl("admin/editSpecs/id/".$ids[1]);
			} else {
				$this->view->errorMessage = 'Va rugam completati toate campurile!';
				$this->view->form = $form;
				return;
			}
		}
		$this->view->form = $form;
	}
	
	public function delspecAction(){
		$ids = explode("_", $this->_getParam('id'));
		
		$mapper = new Application_Model_SpecificationMapper();
		 
		if ($mapper->delete($ids[0]) == 1){
			//One row was deleted
			return $this->_helper->redirector->gotoUrl('admin/editSpecs/id/'.$ids[1]);
		} else {
			return $this->_helper->redirector('index');
		}
	}
	
    public function categoriesAction(){

    	$categMapper = new Application_Model_CategoryMapper();
    	$categs = $categMapper->fetchAll();

    	$this->view->contentCategories = "<a href='/admin/addCategory'>Creeaza Categorie</a><br />";

    	if (empty($categs)){
    		$this->view->contentCategories.= "<h4>Nu exista categorii!</h4>";
    	} else{
    		$this->view->contentCategories.= "<table><thead style='font-weight:bold;'>
    				<tr><td>ID</td> <td>Nume</td> <td>Descriere</td> <td>Actiuni</td></tr></thead>";
    		foreach($categs as $category){

    			$this->view->contentCategories.="<tr>";

    			$this->view->contentCategories.="<td>".$category->getId_category()."</td>";
    			$this->view->contentCategories.="<td>".$category->getName()."</td>";
    			$this->view->contentCategories.="<td>".$category->getDescription()."</td>";
    			$this->view->contentCategories.="<td><a id='".$category->getId_category()."' class='deleteCateg' href='#'>Sterge</a> /
    												<a id='".$category->getId_category()."' class='editCateg' href='#'>Modifica</a></td>";

    			$this->view->contentCategories.="</tr>";
    		}
    		$this->view->contentCategories.= "</table>";
    	}
    }

    public function addcategoryAction(){
    	$request = $this->getRequest();
    	$form = new Application_Form_AddCategory();
    	
    	if ($this->getRequest()->isPost()) {
    		if ($form->isValid($request->getPost())) {
    			$category = new Application_Model_Category($form->getValues());
    			$mapper  = new Application_Model_CategoryMapper();
    			$mapper->save($category);
    			return $this->_helper->redirector('categories');
    		}
    	}
    	$this->view->form = $form;
    }

    public function delcategoryAction(){
    	$categId = $this->_getParam('id');
    	$mapper  = new Application_Model_CategoryMapper();
    	
    	if ($mapper->delete($categId) == 1){
    		//One row was deleted
    		return $this->_helper->redirector('categories');
    	} else {
    		return $this->_helper->redirector('index');
    	}
    }
    
    public function editcategoryAction(){
    	$categId = $this->_getParam('id');
    	$mapper  = new Application_Model_CategoryMapper();
    	$request = $this->getRequest();
    	$form = new Application_Form_AddCategory();
    	
    	$category = new Application_Model_Category();
    	$mapper->find($categId, $category);
    	
    	$form->getElement('name')->setValue($category->getName());
    	$form->getElement('description')->setValue($category->getDescription());
    	$form->getElement('submit')->setLabel('Modifica');
    	 
    	if ($this->getRequest()->isPost()) {
    		if ($form->isValid($request->getPost())) {
    			$newCategory = new Application_Model_Category($form->getValues());
    			$newCategory->setId_category($categId);
    			
    			$mapper->save($newCategory);
    			return $this->_helper->redirector('categories');
    		}
    	}
    	$this->view->form = $form;
    }

    public function offersAction(){
    	$productMapper = new Application_Model_ProductMapper();
    	$offerMapper = new Application_Model_OfferMapper();
    	$offers = $offerMapper->fetchAll();
    	
    	$this->view->contentOffers = "<a href='/admin/addOffer'>Creeaza Oferta</a><br />";
    	
    	if (empty($offers)){
    		$this->view->contentOffers.= "<h4>Nu exista oferte!</h4>";
    	} else {
    		$this->view->contentOffers.= "<table><thead style='font-weight:bold;'>
    				<tr><td>ID</td> <td>Produs</td> <td>Data Inceput</td>
    				<td>Data Sfarsit</td> <td>Reducere</td> <td>Inca activa</td> <td>Actiuni</td></tr></thead>";
    		foreach($offers as $offer){
    			$productOffer = new Application_Model_Product();
    			$productMapper->find($offer->getId_product(), $productOffer);
    			 
    			$this->view->contentOffers.="<tr>";
    	
    			$this->view->contentOffers.="<td>".$offer->getId()."</td>";
    			$this->view->contentOffers.="<td>".($productOffer->getName() != null ? $productOffer->getName() : "Produs Inexistent!" )."</td>";
    			$this->view->contentOffers.="<td>".date('d/m/Y', strtotime($offer->getBegin()))."</td>";
    			$this->view->contentOffers.="<td>".date('d/m/Y', strtotime($offer->getEnd()))."</td>";
    			$this->view->contentOffers.="<td>".$offer->getPrice_reduction()." %</td>";
    			$this->view->contentOffers.="<td>".($offer->getBegin() <= $offer->getEnd() ? "Activa" : "Inactiva")."</td>";
    			 
    			$this->view->contentOffers.="<td><a id='".$offer->getId()."' class='deleteOffer' href='#'>Sterge</a> /
    												<a id='".$offer->getId()."' class='editOffer' href='#'>Modifica</a></td>";
    	
    			$this->view->contentOffers.="</tr>";
    		}
    		$this->view->contentOffers.= "</table>";
    	}
    	
    }

    public function addofferAction(){
    	$request = $this->getRequest();
    	$form = new Application_Form_AddOffer();
    	
    	if ($this->getRequest()->isPost()) {
    		if ($form->isValid($request->getPost()) && $form->getValue('id_product') != 0) {
    			
    			if ($form->getValue('begin') >= $form->getValue('end')){
    				$this->view->errorMessage = 'Data de inceput trebuie sa fie anterioara datei de sfarsit!';
    				$this->view->form = $form;
    				return;
    			}
    			
    			if ($form->getValue('price_reduction') > 100){
    				$this->view->errorMessage = 'Reducerea (procentaj) nu poate fi mai mare decat pretul!';
    				$this->view->form = $form;
    				return;
    			}
    			
				$offer = new Application_Model_Offer($form->getValues());
				$mapper = new Application_Model_OfferMapper();
				$mapper->save($offer);
				return $this->_helper->redirector('offers');
    		} else if ($form->getValue('id_product') == 0){
    			$this->view->errorMessage = 'Va rugam selectati un produs!';
    			$this->view->form = $form;
    			return;
    		}
    	}    	
    	$this->view->form = $form;
    }
    
    public function delofferAction(){
    	$offerId = $this->_getParam('id');
    	$mapper = new Application_Model_OfferMapper();
    	 
    	if ($mapper->delete($offerId) == 1){
    		//One row was deleted
    		return $this->_helper->redirector('offers');
    	} else {
    		return $this->_helper->redirector('index');
    	}
    }
    
    public function editofferAction(){
    	$offerId = $this->_getParam('id');
    	$offerMapper = new Application_Model_OfferMapper();
    	$productMapper = new Application_Model_ProductMapper();
    	$request = $this->getRequest();
    	$form = new Application_Form_EditOffer();
    	
    	$oldOffer = new Application_Model_Offer();
    	$product = new Application_Model_Product();
    	$offerMapper->find($offerId, $oldOffer);
    	$productMapper->find($oldOffer->getId_product(), $product).
    	
    	$form->getElement('id_product')->setValue($product->getName());
    	
    	$form->getElement('price_reduction')->setValue($oldOffer->getPrice_reduction());
    	
    	//format the date according to dojo standards
    	$form->getElement('begin')->setValue(date_format(date_create($oldOffer->getBegin()), 'Y-m-d'));
    	$form->getElement('end')->setValue(date_format(date_create($oldOffer->getEnd()), 'Y-m-d'));
    	
    	
    	if ($this->getRequest()->isPost()) {    		
    		if ($form->isValid($request->getPost())) {   			
    			if ($form->getValue('begin') >= $form->getValue('end')){
    				$this->view->errorMessage = 'Data de inceput ('.$form->getValue('begin').') trebuie sa fie anterioara datei de sfarsit '.$form->getValue('end').' !';
    				$this->view->form = $form;
    				return;
    			}
    			 
    			if ($form->getValue('price_reduction') > 100){
    				$this->view->errorMessage = 'Reducerea (procentaj) nu poate fi mai mare decat pretul!';
    				$this->view->form = $form;
    				return;
    			}
    			 
    			$newOffer = new Application_Model_Offer($form->getValues());
    			$newOffer->setId($offerId);
    			$newOffer->setId_product($oldOffer->getId_product());
    			
    			$offerMapper->save($newOffer);
    			return $this->_helper->redirector('offers');
    		}
    	}
    	$this->view->form = $form;
    }
    
    public function ordersAction(){
    	$cartMapper = new Application_Model_CartMapper();
    	$cartProductMapper = new Application_Model_CartProductMapper();
    	$productMapper = new Application_Model_ProductMapper();
    	$userMapper = new Application_Model_UserMapper();
    	$orderMapper = new Application_Model_ApprovedOrderMapper();
    	$productOrderMapper = new Application_Model_ProductOrderMapper();
    	
    	$carts = $cartMapper->fetchAll();
    	$cartProducts = $cartProductMapper->fetchAll();
    	

    	$this->view->contentOrders = "<h3>Situatie vanzari</h3>";
    	if (empty($carts)){
    		$this->view->contentOrders.= "<h4>Nu exista vanzari incheiate sau in curs!</h4>";
    	} else {
    		$this->view->contentOders.= '<table><thead style="font-weight:bold;">
    						<tr><td>ID Cos</td> <td>Produse</td> <td>Stare</td>
    						<td>Utilizator</td><td>Actiuni</td></tr></thead>';
    		
    		//Go through shopping carts and display products, state and user information
    		foreach($carts as $cart){
    			$productIds = $cartProductMapper->getProductIdsForCart($cart->getId());
    			$products = $productMapper->fetchAllWithIds($productIds);
    			$cartOwner = $userMapper->getByCart($cart->getId());
    			
    			$this->view->contentOders.= '<tr>';
    			
    			$this->view->contentOffers.="<td>".$cart->getId()."</td>";
    			
    			$this->view->contentOffers.='<td>';
    			if (empty($products)){
    				$this->view->contentOffers.='Nu exista produse in acest cos de cumparaturi.';
    			} else {
    				$this->view->contentOffers.='<ol>';
    				foreach($products as $product){
    					$this->view->contentOffers.='<li>';
    					$this->view->contentOffers.= $product->getName();
    					$this->view->contentOffers.='</li>';
    				}
    				$this->view->contentOffers.='</ol>';
    			}
    			
    			$this->view->contentOffers.='</td>';
    			
    			$this->view->contentOffers.="<td>".($cart->getChecked_out() ? "Validat" : "In asteptare")."</td>";
    			$this->view->contentOffers.="<td>".strtoupper($cartOwner->getLast_name()) ." ".$cartOwner->getFirst_name()."</td>";
    			$this->view->contentOffers.="<td>".($cart->getChecked_out() ?
    														 "<a id='".$cart->getId()."' class='approveOrder' href='#'>Aproba comanda</a>" : 
    														"Nicio actiune disponibila")."</td>";
    			
    			$this->view->contentOders.= '</tr>';
    		}
    		$this->view->contentOders.= '</table>';
    	}
    	
    	$this->view->contentOrders.= "<h3>Comenzi aprobate / expediate</h3>";
    	
    	$orders = $orderMapper->fetchAll();
    	if (empty($orders)){
    		$this->view->contentOrders.= "<h4>Nu exista comenzi aprobate / expediate</h4>";
    	} else{
    		$this->view->contentOrders.= '<table><thead style="font-weight:bold;">
    						<tr><td>ID </td> <td>Utilizator</td> <td>Produse</td>
    						<td>Data aprobare</td></tr></thead>';
    		
    		foreach($orders as $order){
    			$orderOwner = new Application_Model_User();
    			$userMapper->find($order->getIdUser(), $orderOwner);
    			$productIds = $productOrderMapper->getProductIdsForOrder($order->getId());
    			$products = $productMapper->fetchAllWithIds($productIds);
    			
    			$this->view->contentOrders.= "<tr>";
    			
    			$this->view->contentOrders.= '<td>'.$order->getId().'</td>';
    			$this->view->contentOrders.= '<td>'.strtoupper($orderOwner->getLast_name()) .' '.$orderOwner->getFirst_name().'</td>';
    			
    			$this->view->contentOrders.= '<td><ol>';
    			foreach($products as $product){
    				$this->view->contentOffers.='<li>';
    				$this->view->contentOffers.= $product->getName();
    				$this->view->contentOffers.='</li>';
    			}
    			$this->view->contentOrders.= '</ol></td>';
    			
    			$this->view->contentOrders.= '<td>'.$order->getApprovedOn().'</td>';
    			$this->view->contentOrders.= "</tr>";
    		}
    		
    		$this->view->contentOrders.= "</table>";
    	}
    }
    
    public function approveorderAction(){
    	$id_cart = $this->_getParam('cart');
    	$userMapper = new Application_Model_UserMapper();
    	$orderMapper = new Application_Model_ApprovedOrderMapper();
    	$productOrderMapper = new Application_Model_ProductOrderMapper();
    	$cartProductMapper = new Application_Model_CartProductMapper();
    	$productMapper = new Application_Model_ProductMapper();
    	
    	$cartOwner = $userMapper->getByCart($id_cart);
    	
    	
    	//send mail to user
    	$front = Zend_Controller_Front::getInstance();
		$bootstrap = $front->getParam('bootstrap');
		$smtpSettings = $bootstrap->getOption('smtp');
		   	
		$config = array('ssl' => $smtpSettings['ssl'],
		  			'username' => $smtpSettings['username'],
		  			'password' => $smtpSettings['password'],
		  			'port' => $smtpSettings['port'],
		  			'auth' => $smtpSettings['auth']);
		    	
		$transport = new Zend_Mail_Transport_Smtp( $smtpSettings['smtpServer'], $config );
		$orderMail = new Zend_Mail();
		Zend_Mail::setDefaultTransport($transport);
		    	
    	$orderMail->setSubject("Comanda .dvs a fost trimisa!");
    	$orderMail->setBodyText("Va multumim pentru comanda facuta!");
    	//TODO add products that where ordered
    	$orderMail->setFrom("admin@estore.com","Cumparaturi pe eStore");
    	$orderMail->addTo("ctln.pgs@gmail.com","Totosel");
    	//$orderMail->addTo($cartOwner->getEmail(),strtoupper($cartOwner->getLast_name()) ." ". $cartOwner->getFirst_name());
    	$orderMail->send();
   	
    	//add row to approved order
    	$order = new Application_Model_ApprovedOrder();
    	$order->setIdUser($cartOwner->getId_user());
    	//TODO date ??
    	$order->setApprovedOn(Zend_Date::now());
    	$id_order= $orderMapper->save($order);
    	
    	//add products to product_order
    	$productIds = $cartProductMapper->getProductIdsForCart($id_cart);
    	foreach($productIds as $id_product){
    		$productOrder = new Application_Model_ProductOrder();
    		$productOrder->setIdOrder($id_order);
    		$productOrder->setIdProduct($id_product);
    		$productOrderMapper->save($productOrder);
    		
    		//decrease product stock (nbr_pieces)
    		$productMapper->decreaseStock($id_product);
    	}
    	
    	//empty cart
    	$cartProductMapper->deleteForCart($id_cart);   

    	return $this->_helper->redirector('orders');
    }

    public function usersAction(){
    	$userMapper = new Application_Model_UserMapper();
    	$users = $userMapper->fetchAll();
    	
    	$this->view->contentUsers = "<a href='/admin/addUser'>Adauga Utilizator</a><br />";
    	
    	$this->view->contentUsers.= "<table><thead style='font-weight:bold;'>
    				<tr><td>ID</td> <td>Nume</td> <td>Prenume</td> 
    				<td>e-mail</td> <td>Adresa</td> <td>Admin</td> <td>Actiuni</td></tr></thead>";
    	foreach($users as $user){
    		$this->view->contentUsers.= '<tr>';
    		
    		$this->view->contentUsers.= '<td>'.$user->getId_user().'</td>';
    		$this->view->contentUsers.= '<td>'.$user->getLast_name().'</td>';
    		$this->view->contentUsers.= '<td>'.$user->getFirst_name().'</td>';
    		$this->view->contentUsers.= '<td>'.$user->getEmail().'</td>';
    		$this->view->contentUsers.= '<td>'.$user->getAddress().'</td>';
    		$this->view->contentUsers.= '<td>'.($user->getIs_admin() ? "Da" : "Nu").'</td>';
    		$this->view->contentUsers.= "<td><a id='".$user->getId_user()."' class='deleteUser' href='#'>Sterge</a></td>";
    		
    		$this->view->contentUsers.= '</tr>';
    	}    	
    	$this->view->contentUsers.= "</table>";
    }
    
    public function deluserAction(){
    	$id_user = $this->_getParam('id');
    	$mapper = new Application_Model_UserMapper();
    	 
    	if ($mapper->delete($id_user) == 1){
    		//One row was deleted
    		return $this->_helper->redirector('users');
    	} else {
    		return $this->_helper->redirector('index');
    	}
    }
    
    public function adduserAction(){
    	$request = $this->getRequest();
    	$form = new Application_Form_AddUser();
    	
    	if ($this->getRequest()->isPost()) {
    		if ($form->isValid($request->getPost())) {
     			$user = new Application_Model_User($form->getValues());
     			$mapper  = new Application_Model_UserMapper();
     			$mapper->save($user);
    			
    			return $this->_helper->redirector('users');
    			
    		}
    	}
    	$this->view->form = $form;
    }

    public function mediaAction(){
    	//TODO file browser on server files
    	//TODO add file functionality
    }
}
